|
|
|
|
|
|
|
clsMyClass is the runtime object instance of CMyClass. Implied with this idea are a runtime architecture and a design-time architecture. CMyClass can be instantiated any number of times at runtime into objects. As stated earlier, objects are cookies. Classes (specifically, concrete classes) are cookie cutters. At design time, a method for CMyClass might be displayMessage. This method accepts two arguments: One is the text box control; the other is a string variable that has the value you want to display. Now let's continue. Assume that Form1 has a text control, Text1, in which you want to display some data. In some Click event, you would do the following: |
|
|
|
|
|
|
|
|
Private Sub Form_Click
Dim vReturns As Variant 'Some return variable. Explicitly declared
'Variant
Set clsMyClass = New CMyClass 'Memory alloc
vReturns = clsMyClass.displayMessage(Text1, Hello, mom)
End Sub |
|
|
|
|
|
|
|
|
In CMyClass, you might implement displayMessage as follows: |
|
|
|
|
|
|
|
|
Public Function displayMessage(ByRef argTextBox, argDisplayString As String)
On Error GoTo displayMessageErr
If TypeOf argTextBox Is TextBox Then
argTextBox.Text = argDisplayString
End If
Exit Function
displayMessageErr:
Err.Raise vbError + 1001, Err.Description 'Something like this to
'raise errors
End Function |
|
|
|
|
|
|
|
|
Here, the only thing the form cares about is that as long as CMyClass received a text box and a string, the class will deliver the promised goods via the displayMessage method. What actually goes on inside the method is none of the form's business. This is encapsulation, which evolved from information hiding. This greatly minimizes the risk of spaghetti code, makes the code easier to read, and encourages reuse throughout the enterprise in case other teams need similar class behavior. Keep in mind that not every class will always be easy to identify and create. You must continually refine classes to carry out clear duties and maximize chances of reuse. |
|
|
|
|
|
|
|
|
Note The lowercase d in the method displayMessage is an idiom in the OOP community for naming methods. |
|
|
|
|
|
|
|
|
|
Time and again, I have seen spaghetti Visual Basic code in which the forms do everything. It's hard to decipher what's going on and to make wise project decisions based on |
|
|
|
|
|